import qrcode
import io
import logging
from typing import Dict, Optional

logger = logging.getLogger(__name__)

class ToolsService:
    @staticmethod
    def generate_qrcode(content: str, options: Dict = None) -> bytes:
        """
        生成二维码
        
        Args:
            content: 二维码内容
            options: 二维码选项
                - size: 尺寸 (1-40)
                - border: 边框宽度
                - fill_color: 填充颜色
                - back_color: 背景颜色
        
        Returns:
            bytes: 二维码图片数据
        """
        try:
            # 默认选项
            default_options = {
                'size': 10,
                'border': 4,
                'fill_color': 'black',
                'back_color': 'white'
            }
            
            # 合并选项
            if options:
                default_options.update(options)
            
            # 创建二维码
            qr = qrcode.QRCode(
                version=default_options['size'],
                error_correction=qrcode.constants.ERROR_CORRECT_L,
                box_size=10,
                border=default_options['border']
            )
            
            qr.add_data(content)
            qr.make(fit=True)
            
            # 生成图片
            img = qr.make_image(
                fill_color=default_options['fill_color'],
                back_color=default_options['back_color']
            )
            
            # 转换为字节
            img_byte_arr = io.BytesIO()
            img.save(img_byte_arr, format='PNG')
            img_byte_arr = img_byte_arr.getvalue()
            
            return img_byte_arr
            
        except Exception as e:
            logger.error(f"生成二维码失败: {str(e)}")
            raise

    @staticmethod
    def process_text(text: str, operation: str) -> str:
        """
        文本处理
        
        Args:
            text: 要处理的文本
            operation: 操作类型 (upper/lower/capitalize/title)
        
        Returns:
            str: 处理后的文本
        """
        try:
            if operation == 'upper':
                return text.upper()
            elif operation == 'lower':
                return text.lower()
            elif operation == 'capitalize':
                return text.capitalize()
            elif operation == 'title':
                return text.title()
            else:
                raise ValueError(f"不支持的操作: {operation}")
                
        except Exception as e:
            logger.error(f"文本处理失败: {str(e)}")
            raise 